package services

import (
	"encoding/json"
	"errors"
	"lingc/models"
	"lingc/utils"
	"strconv"
	"strings"
	"time"

	"gorm.io/gorm"
)

// ChatAutoReplyService 提供账号登录校验的服务
type ChatAutoReplyService struct {
	DB *gorm.DB
}

// NewChatAutoReplyService 创建一个新的 ChatAutoReplyService 实例
func NewChatAutoReplyService(db *gorm.DB) *ChatAutoReplyService {
	return &ChatAutoReplyService{DB: db}
}

//表单业务

/**
 * @Description: 分页获取权限组列表
 * @param where
 * @param page
 * @param pageSize
 * @return []*models.ChatAutoReply
 * @return int
 * @return int64
 * @return error
 */
func (s *ChatAutoReplyService) PageChatAutoReplyList(where string, page, pageSize int) ([]*models.ChatAutoReplyList, int, int64, error) {
	var groups []*models.ChatAutoReply
	var total int64

	// 计算偏移量
	offset := (page - 1) * pageSize

	// 获取总记录数
	if err := s.DB.Model(&models.ChatAutoReply{}).Where(where).Count(&total).Error; err != nil {
		return nil, 1, 0, err
	}

	// 获取分页数据
	if err := s.DB.Where(where).Preload("AuthUser").Offset(offset).Limit(pageSize).Order("id DESC").Find(&groups).Error; err != nil {
		return nil, 1, 0, err
	}
	var list []*models.ChatAutoReplyList
	list = []*models.ChatAutoReplyList{}
	for _, data := range groups {
		list = append(list, &models.ChatAutoReplyList{
			ID:        data.ID,
			AdminID:   data.AdminID,
			AdminName: data.AuthUser.Username,
			Type:      data.Type,
			Title:     data.Title,
			Content:   data.Content,
			MsgType:   data.MsgType,
			Status:    data.Status,
			Sort:      data.Sort,
			CreatedAt: time.Unix(data.CreatedAt, 0).Format("2006-01-02 15:04:05"), // 格式化时间戳
			UpdatedAt: time.Unix(data.UpdatedAt, 0).Format("2006-01-02 15:04:05"), // 格式化时间戳
		})
	}

	return list, page, total, nil
}

/**
 * @Description: 创建新权限组
 * @param username
 * @param password
 * @param realname
 * @param avatar
 * @param status
 * @return *models.ChatAutoReplyCreate
 * @return error
 */
func (s *ChatAutoReplyService) CreateChatAutoReply(data *models.ChatAutoReplyCreate) (*models.ChatAutoReplyCreate, error) {
	// 检查权限组名是否已存在
	addData := &models.ChatAutoReply{
		AdminID:   data.AdminID,
		Title:     data.Title,
		Content:   data.Content,
		Type:      data.Type,
		MsgType:   data.MsgType,
		Status:    data.Status,
		Sort:      data.Sort,
		CreatedAt: time.Now().Unix(),
		UpdatedAt: time.Now().Unix(),
	}
	// 保存新权限组到数据库
	if err := s.DB.Create(addData).Error; err != nil {
		return nil, err
	}
	return data, nil
}

// GetChatAutoReply 获取权限组信息
func (s *ChatAutoReplyService) GetChatAutoReply(where string) (*models.ChatAutoReply, error) {
	var data models.ChatAutoReply
	if err := s.DB.Where(where).First(&data).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("权限组不存在")
		}
		return nil, err
	}
	// log.Printf("data_info:%v", data)
	return &data, nil
}

/**
 * @Description: 更新权限组信息
 * @param data
 * @return error
 */
func (s *ChatAutoReplyService) UpdateChatAutoReply(data *models.ChatAutoReplyUpdate) (*models.ChatAutoReplyUpdate, error) {
	// 检查权限组名是否已存在
	var existingUser models.ChatAutoReply
	if err := s.DB.Where("id = ?", data.ID).First(&existingUser).Error; err != nil {
		return nil, errors.New("数据不存在")
	}
	existingUser.AdminID = data.AdminID
	existingUser.Title = data.Title
	existingUser.MsgType = data.MsgType
	existingUser.Type = data.Type
	existingUser.Status = data.Status
	existingUser.Sort = data.Sort
	existingUser.Content = data.Content
	existingUser.UpdatedAt = time.Now().Unix()
	return data, s.DB.Save(existingUser).Error
}

/**
 * @Description: 删除权限组
 * @param id
 * @return error
 */
func (s *ChatAutoReplyService) DeleteChatAutoReply(id uint) error {
	var data models.ChatAutoReply
	if err := s.DB.Where("id = ?", id).First(&data).Error; err != nil {
		return errors.New("数据不存在")
	}
	return s.DB.Delete(&data).Error
}

/**
 * @Description: 批量删除权限组
 * @param id
 * @return error
 */
func (s *ChatAutoReplyService) DeleteChatAutoReplys(ids []string) error {
	var data models.ChatAutoReply
	for _, id := range ids {
		if err := s.DB.Where("id = ?", id).First(&data).Error; err != nil {
			return errors.New("数据不存在")
		}
		err := s.DB.Delete(&data).Error
		if err != nil {
			return errors.New("删除失败")
		}
	}
	return nil
}

// 获取数据
func (s *ChatAutoReplyService) GetChatAutoReplyData(admin_id uint, msg_type uint8) ([]*models.ChatAutoReply, error) {
	var data []*models.ChatAutoReply

	jsonStr := utils.GetRedis("chat_auto_reply_data_" + strconv.Itoa(int(admin_id)) + strconv.Itoa(int(msg_type)))
	if jsonStr != "" {
		err := json.Unmarshal([]byte(jsonStr), &data)
		if err != nil {
			return nil, err
		}
		return data, nil
	}
	err := s.DB.Where("admin_id = ?", admin_id).Where("msg_type = ?", msg_type).Order("sort DESC").Find(&data).Error
	if err != nil {
		return nil, err
	}
	if len(data) > 0 {
		jsonStr, _ := json.Marshal(data)
		utils.SetRedis("chat_auto_reply_data_"+strconv.Itoa(int(admin_id))+strconv.Itoa(int(msg_type)), string(jsonStr), 60)
	}
	return data, nil
}

// GetLikeTitleReply 根据标题获取自动回复
func (s *ChatAutoReplyService) GetLikeTitleReply(admin_id uint, title string) (*models.ChatAutoReply, error) {
	var dataList []*models.ChatAutoReply
	jsonStr := utils.GetRedis("chat_auto_reply_like_title_data_" + strconv.Itoa(int(admin_id)) + "2")
	if jsonStr != "" {
		err := json.Unmarshal([]byte(jsonStr), &dataList)
		if err != nil {
			return nil, err
		}
		for _, item := range dataList {
			if strings.Contains(item.Title, title) {
				return item, nil
			}
		}
	}
	err := s.DB.Where("admin_id = ? and title like ? and status = ? and msg_type = ?", admin_id, "%"+title+"%", 1, 2).Order("sort DESC").First(&dataList).Error
	if err != nil {
		return nil, err
	}
	if len(dataList) > 0 {
		jsonStr, _ := json.Marshal(dataList)
		utils.SetRedis("chat_auto_reply_data_"+strconv.Itoa(int(admin_id))+"2", string(jsonStr), 60)
	}
	for _, item := range dataList {
		if strings.Contains(item.Title, title) {
			return item, nil
		}
	}
	return nil, nil
}
